package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.hmdp.utils.RedisConstants.USER_SIGN_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
   @Resource
   private StringRedisTemplate stringRedisTemplate;
    public Result signCount() {
    Long userId= UserHolder.getUser().getId();
    //获取日期
    LocalDateTime now=LocalDateTime.now();
    //拼接key
    String keySuffix=now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
    String key=USER_SIGN_KEY+userId+keySuffix;
    //获取今天是本月第几天
    int dayofMonth=now.getDayOfMonth();
        List<Long> result=stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayofMonth)).valueAt(0));
        if(result == null ||result.isEmpty()){
            return Result.ok(0);
        }
        Long num=result.get(0);
        if(num == null || num == 0){
            return Result.ok(0);
        }
        int count=0;
        while (true){
            // 6.1.让这个数字与1做与运算，得到数字的最后一个bit位  // 判断这个bit位是否为0
            if((num&1)==0){
                //如果0，未签到，结束
                break;
            }else {
                count++;
            }
            num>>>=1;
        }
        return Result.ok(count);

    }
    public   Result sign(){
        Long userId=UserHolder.getUser().getId();
        LocalDateTime now=LocalDateTime.now();
        String keySuffix=now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=USER_SIGN_KEY+userId+keySuffix;
        int dayofmonth=now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key,dayofmonth-1,true);
        return Result.ok();
    }
}
